﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using Haimen.Excel;

namespace Haimen;

internal class AppConfigReader(ExcelFileUtils excelUtil) {

  public AppConfigRoot Read(DataGroupCfg[] groupAll, string lookupPath) {
    Dictionary<string, DataHeaderCfg[]> headerDict =
      groupAll.ToDictionary(g => g.Name, g => g.Header);

    using FileStream stream = _excelUtil.OpenRead(lookupPath);
    using XLWorkbook lookupBook = new(stream);

    IXLWorksheet sheet = lookupBook.Worksheet(1);
    Dictionary<string, string> lookupDict = MakeLookupDict(sheet);
    return new(headerDict, lookupDict);
  }

  Dictionary<string, string> MakeLookupDict(IXLWorksheet sheet) {
    var CellStr = (int r, int c) => sheet.Cell(r, c).GetString();

    return Enumerable
      .Range(1, LastRowNum(sheet))
      .ToDictionary(r => CellStr(r, 1), r => CellStr(r, 2));
  }
  int LastRowNum(IXLWorksheet sheet) {
    return sheet.LastRowUsed(XLCellsUsedOptions.All).RowNumber();
  }

  readonly ExcelFileUtils _excelUtil = excelUtil;
}

internal record AppConfigRoot(
  Dictionary<string, DataHeaderCfg[]> Header, Dictionary<string, string> Lookup);
